const { Sequelize } = require('sequelize');
const config = require('./index');
const { logger } = require('../utils/logger');

const MAX_RETRIES = 5;
const RETRY_DELAY = 5000; // 5 seconds

/**
 * 创建Sequelize实例
 * @returns {Sequelize} - Sequelize实例
 */
const createSequelizeInstance = () => {
  return new Sequelize(
    config.database.name,
    config.database.user,
    config.database.password,
    {
      host: config.database.host,
      port: config.database.port,
      dialect: 'mysql',
      logging: (msg) => logger.debug(msg),
      pool: {
        max: config.database.pool.max || 10,
        min: config.database.pool.min || 0,
        acquire: config.database.pool.acquire || 30000,
        idle: config.database.pool.idle || 10000
      },
      define: {
        timestamps: true,
        underscored: true,
        paranoid: true // Soft deletes
      }
    }
  );
};

const sequelize = createSequelizeInstance();

/**
 * 测试数据库连接
 * @param {number} retries - 重试次数
 */
const connectWithRetry = async (retries = MAX_RETRIES) => {
  try {
    await sequelize.authenticate();
    logger.info('Database connection has been established successfully.');
  } catch (error) {
    logger.error('Unable to connect to the database:', error);
    if (retries > 0) {
      logger.info(`Retrying connection in ${RETRY_DELAY/1000} seconds... (${retries} attempts remaining)`);
      setTimeout(() => connectWithRetry(retries - 1), RETRY_DELAY);
    }
  }
};

// 测试数据库连接
connectWithRetry();

module.exports = sequelize; 